#include "widget.h"
#include "ui_widget.h"
#include<QDataStream>//流
#include<QMessageBox>
#include<QDateTime>
#include<QComboBox>
#include<QColorDialog>
Widget::Widget(QWidget *parent,QString name)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    //this->setWindowTitle();
    myname=name;
    //绑定端口
    this->port=9999;
    this->udpsocket=new QUdpSocket(this);

    udpsocket->bind(port,QUdpSocket::ShareAddress|QUdpSocket::ReuseAddressHint);

    connect(udpsocket,&QUdpSocket::readyRead,this,&Widget::receivemassage);

    //连接发送按钮
    connect(ui->pushButton,&QPushButton::clicked,[=](){
        sndMsg(Msg);

    });
    sndMsg(UserEnter);

    connect(ui->pushButton_2,&QPushButton::clicked,[=](){
        this->close();
    });

    connect(ui->fontComboBox,&QFontComboBox::currentFontChanged,[=](const QFont &font){
       ui->textEdit->setFontFamily(font.toString());
       ui->textEdit->setFocus();

    });
    void (QComboBox:: * sizebtn) (const QString &text)=&QComboBox::currentTextChanged;

    connect(ui->comboBox,sizebtn,[=](const QString &text){

        ui->textEdit->setFontPointSize(text.toDouble());
        ui->textEdit->setFocus();
    });

    connect(ui->toolButton,&QToolButton::clicked,[=](bool checked){
       if(checked)
       {
           ui->textEdit->setFontWeight(QFont::Bold);
       }
       else
       {
            ui->textEdit->setFontWeight(QFont::Normal);
       }
    });
    connect(ui->toolButton_2,&QToolButton::clicked,[=](bool checked2){
           ui->textEdit->setFontItalic(checked2);
           ui->textEdit->setFocus();
    });
    connect(ui->toolButton_3,&QToolButton::clicked,[=](bool checked3){
        ui->textEdit->setFontUnderline(checked3);
        ui->textEdit->setFocus();
    });
    connect(ui->toolButton_6,&QToolButton::clicked,[=](){
        ui->textBrowser->clear();
    });
    connect(ui->toolButton_4,&QToolButton::clicked,[=](){
       QColor color= QColorDialog::getColor(color,this);
       ui->textEdit->setTextColor(color);

    });
}
//void Widget::closeEvent(QCloseEvent*)
//{
//    //emit this->close();
//    sndMsg(UserLeft);

//    udpsocket->close();
//    udpsocket->destroyed();

//}

void Widget::sndMsg(Widget::Msgtype type)//发送信息
{
   QByteArray  array;
   QDataStream stream(&array,QIODevice::WriteOnly);
   stream<<type<<this->getname();

   switch (type) {
   case Msg:
       if(ui->textEdit->toPlainText()=="")
       {
           QMessageBox::warning(this,"警告","超级警告");
           return;
       }
       stream<<this->getMsg();
       break;
   case UserEnter:

   case UserLeft:
   default:
       break;
   }
  //书写报文
   udpsocket->writeDatagram(array.data(),array.size(),QHostAddress::Broadcast,this->port);

}


QString Widget::getname()
{
    return this->myname;
}

QString Widget::getMsg()//获取聊天内容
{
    QString msg=ui->textEdit->toHtml();//添加文字
    ui->textEdit->clear();
    ui->textEdit->setFocus();
    return msg;
}
void Widget::userEnter(QString username)
{
    bool Isempty=ui->tableWidget->findItems(username,Qt::MatchExactly).isEmpty();
    if(Isempty)
    {
        QTableWidgetItem *table=new QTableWidgetItem(username);
        ui->tableWidget->insertRow(0);
        ui->tableWidget->setItem(0,0,table);
        ui->textBrowser->setTextColor(QColor(Qt::gray));
        ui->textBrowser->append(username+"已上线");
        ui->label->setText(QString("在线人数:%1").arg(ui->tableWidget->rowCount()));
        sndMsg(UserEnter);
    }


}
void Widget::userleft(QString username,QString time)
{
    bool Isempty=ui->tableWidget->findItems(username,Qt::MatchExactly).isEmpty();
    if(!Isempty)
    {
        int row=ui->tableWidget->findItems(username,Qt::MatchExactly).first()->row();

        ui->tableWidget->removeRow(row);

        ui->textBrowser->append(QString("%1用户于%2离开").arg(username).arg(time));
        ui->label->setText(QString("在线人数:%1").arg(ui->tableWidget->rowCount()));

    }


}


void Widget::receivemassage()
{
    qint64 size=udpsocket->pendingDatagramSize();
    int mysize=static_cast<int>(size);
    QByteArray *array=new QByteArray(mysize,0);
    udpsocket->readDatagram((*array).data(),size);
    QDataStream stream(array,QIODevice::ReadOnly);
    int mytype;
    QString name,msg;
    QString time=QDateTime::currentDateTime().toString("yyyy-MM-dd hh-mm-ss");
    stream>>mytype;
    switch (mytype) {
    case Msg:
        stream>>name>>msg;
        ui->textBrowser->setTextColor(QColor(Qt::blue));
         ui->textBrowser->append("["+name+"]"+time);
         ui->textBrowser->append(msg);
        break;

    case UserLeft:
         stream>>name;
         userleft(name,time);
        break;

    case UserEnter:
        stream>>name;
        userEnter(name);

        break;

    default:
        break;
    }
}

void Widget::closeEvent(QCloseEvent *)
{
    emit this->closeWidget();
    sndMsg(UserLeft);
    udpsocket->close();
    udpsocket->destroyed();

}
Widget::~Widget()
{
    delete ui;
}

